package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.AliIoTConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备Service业务层处理
 * 
 * @author xiexiaoyu
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }
    /**
     * 从物联网平台同步产品列表到redis中
     * */
    @Override
    public void syncProductList() {
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(100);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("同步产品列表失败！");
        }

        if(!response.body.success){
            throw new BaseException("同步产品列表失败！");
        }
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productList = response.body.data.list.productInfo;
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_ALL, JSON.toJSONString(productList));
    }

    /**
     * 从redis中获取产品列表
     */
    @Override
    public List<ProductVo> getAllProduct() {
        String productVoStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_ALL);
        List<ProductVo> productVoList = JSONUtil.toList(productVoStr, ProductVo.class);
        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //从数据库中查询设备名称，判断是否重复
        Long count = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        //若重复，结束
        if(count>0){
            throw new BaseException("设备名称重复，请重新输入");
        }
        //未重复，在IOT平台新增设备
        RegisterDeviceResponse response;
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            response = client.registerDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        if(!response.body.success){
            throw new BaseException(response.body.errorMessage);
        }
        // 设置产品名称到设备对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        //判断位置类型是否为0,若为0则将物理位置改为-1
        if(device.getLocationType()==0){
            device.setPhysicalLocationType(-1);
        }
        //补全IOTId
        device.setIotId(response.body.data.iotId);
        //保存设备到数据库
        try {
            int result = deviceMapper.insert(device);
            if(result==0){
                //若保存失败，则删除IPT平台的设备信息
                deleteIOTDevice(device);
                throw new BaseException("保存设备到数据库失败");
            }
        } catch (Exception e) {
            //若保存失败，则删除IPT平台的设备信息
            deleteIOTDevice(device);
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }

    }

    private void deleteIOTDevice(Device device) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotId(device.getIotId());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setDeviceName(device.getDeviceName());
        request.setProductKey(device.getProductKey());
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除设备失败");
        }
    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //从iot平台查询设备详情
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("从IOT获取响应失败");
        }
        if (!response.body.success){
            throw new BaseException("从IOT查询设备详情失败");
        }
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.body.data;
        DeviceVo deviceVo = BeanUtil.toBean(data, DeviceVo.class);
        //从数据库查询设备详情
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        BeanUtil.copyProperties(device,deviceVo);
        //合并返回
        return deviceVo;
    }

    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("查询物模型失败");
        }

        if (!response.body.success){
            throw new BaseException("查询物模型失败");
        }
        return AjaxResult.success(response.body.data);
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("查询物模型失败");
        }
        if (!response.body.success){
            throw new BaseException("查询物模型失败");
        }
        return AjaxResult.success(response.body.data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceRemarkName(Device device) {
        //修改数据库
        deviceMapper.updateById(device);
        //修改IOT平台
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> deviceNicknameInfos = new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo deviceNicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        deviceNicknameInfo.setDeviceName(device.getDeviceName());
        deviceNicknameInfo.setNickname(device.getNickname());
        deviceNicknameInfo.setProductKey(device.getProductKey());
        deviceNicknameInfos.add(deviceNicknameInfo);
        request.setDeviceNicknameInfo(deviceNicknameInfos);
        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("修改设备备注失败");
        }
        if(!response.body.success){
            throw new BaseException("修改设备备注失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(DeviceDto deviceDto) {
        //删除数据库
        deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId,deviceDto.getIotId()));
        //删除IOT平台
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除设备失败");
        }
        if(!response.body.success){
            throw new BaseException("删除设备失败");
        }
    }
}
